<!-- AnnouncementAdd.vue -->
<template>
  <div class="announcement-add-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>公告管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加公告</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="page-header">
      <el-page-header @back="goBack" content="添加公告"></el-page-header>
    </div>

    <el-card class="form-card">
      <el-form
          label-width="100px"
          label-position="top"
          class="announcement-form"
          ref="announcementFormRef"
          :model="announcementForm"
          :rules="formRules">

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公告标题" prop="title">
              <el-input
                  placeholder="请输入公告标题"
                  v-model="announcementForm.title">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公告类型" prop="type">
              <el-select
                  v-model="announcementForm.type"
                  placeholder="请选择公告类型"
                  style="width: 100%;">
                <el-option label="社区公告" value="community"></el-option>
                <el-option label="普法内容" value="legal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告状态" prop="status">
              <el-select
                  v-model="announcementForm.status"
                  placeholder="请选择公告状态"
                  style="width: 100%;">
                <el-option label="草稿" value="draft"></el-option>
                <el-option label="定稿" value="finalized"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公告图片" prop="imageUrl">
              <el-upload
                  class="announcement-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleImageSuccess"
                  :on-error="handleImageError"
                  :before-upload="beforeImageUpload"
                  :disabled="uploading">
                <img v-if="announcementForm.imageUrl" :src="announcementForm.imageUrl" class="announcement-image-preview">
                <el-icon v-else class="announcement-uploader-icon"><Plus /></el-icon>
                <div class="upload-text" v-if="!announcementForm.imageUrl">点击上传图片</div>
              </el-upload>
              <div class="image-url-display" v-if="announcementForm.imageUrl">
                <el-input
                    v-model="announcementForm.imageUrl"
                    readonly
                    class="image-url-input">
                  <template #append>
                    <el-button @click="announcementForm.imageUrl = ''">清除</el-button>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公告内容" prop="content">
              <div class="editor-wrapper">
                <Toolbar
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                    style="border-bottom: 1px solid #ccc"
                />
                <Editor
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    v-model="announcementForm.content"
                    @onCreated="handleCreated"
                    style="height: 300px; overflow-y: hidden;"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <div class="form-buttons">
              <el-button @click="resetForm">重置</el-button>
              <el-button @click="previewAnnouncement">预览</el-button>
              <el-button
                  type="primary"
                  @click="saveAnnouncement"
                  :loading="saving">
                保存公告
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 公告预览弹窗 -->
    <el-dialog
        v-model="previewVisible"
        title="公告预览"
        width="800px"
        class="preview-dialog"
        :before-close="handlePreviewClose">
      <div class="preview-content">
        <div class="preview-header">
          <h2 class="preview-title">{{ announcementForm.title }}</h2>
          <div class="preview-meta">
            <el-tag :type="announcementForm.type === 'community' ? 'primary' : 'success'" class="preview-tag">
              {{ announcementForm.type === 'community' ? '社区公告' : '普法内容' }}
            </el-tag>
            <span class="preview-date">{{ formatDate(new Date()) }}</span>
          </div>
        </div>

        <div v-if="announcementForm.imageUrl" class="preview-image">
          <img :src="announcementForm.imageUrl" alt="公告图片" class="preview-image-content">
        </div>

        <div class="preview-body" v-html="announcementForm.content"></div>
      </div>

      <template #footer>
        <el-button @click="handlePreviewClose">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
// 引入富文本编辑器
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

const router = useRouter()

// 编辑器实例
const editorRef = ref()
const mode = 'default'
// 只保留指定功能的工具栏配置
const toolbarConfig = {
  toolbarKeys: [
    'headerSelect',  // 标题选择
    '|',
    'bold',          // 粗体
    'italic',        // 斜体
    'underline',     // 下划线
    '|',
    'color',         // 字体颜色
    'justifyLeft',   // 左对齐
    'justifyCenter', // 居中
    'justifyRight',  // 右对齐
    '|',
    'undo',          // 撤销
    'redo'           // 重做
  ]
}
const editorConfig = {
  placeholder: '请输入公告内容...',
  MENU_CONF: {
    'uploadImage': {
      // 禁用编辑器图片上传，使用我们自己的上传
      customUpload: () => {}
    },
    // 配置颜色选择器
    'color': {
      colors: [
        '#000000', '#ffffff', '#eeece0', '#1c487f', '#4d80bf',
        '#c24f4a', '#8baa4a', '#7b5ba1', '#46acc8', '#f9963b',
        '#ea5a2e', '#666666', '#999999', '#cccccc', '#e67e22'
      ]
    }
  }
}

// 表单引用
const announcementFormRef = ref(null)

// 上传状态
const uploading = ref(false)
const saving = ref(false)

// 预览状态
const previewVisible = ref(false)

// 上传配置
const uploadUrl = `${BASE_URL}/api/announcements/files/upload`
const uploadHeaders = {
  // 如果需要认证token，可以在这里添加
  // 'Authorization': 'Bearer ' + localStorage.getItem('token')
}

// 表单数据
const announcementForm = reactive({
  announcementId: '',
  title: '',
  content: '', // 富文本内容（HTML格式）
  type: '',
  status: '',
  imageUrl: '',
  createdAt: '',
  updatedAt: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择公告状态', trigger: 'change' }
  ]
}

// 编辑器创建回调
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 组件销毁前清理编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }

  uploading.value = true
  return true
}

// 图片上传成功处理
const handleImageSuccess = (response, uploadFile) => {
  uploading.value = false
  if (response.state === 2001) {
    announcementForm.imageUrl = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

// 保存公告
const saveAnnouncement = () => {
  if (!announcementFormRef.value) return

  announcementFormRef.value.validate((valid) => {
    if (valid) {
      saving.value = true

      axios.post(BASE_URL + '/api/announcements/add', announcementForm)
          .then((response) => {
            if (response.data.state === 2001) {
              ElMessage.success('公告添加成功！')
              ElMessageBox.confirm(
                  '公告添加成功，是否继续添加新公告？',
                  '操作成功',
                  {
                    confirmButtonText: '继续添加',
                    cancelButtonText: '返回列表',
                    type: 'success',
                  }
              )
                  .then(() => {
                    resetForm()
                  })
                  .catch(() => {
                    goBack()
                  })
            } else {
              ElMessage.error(response.data.msg)
            }
          })
          .catch((error) => {
            ElMessage.error('保存失败：' + error.message)
          })
          .finally(() => {
            saving.value = false
          })
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(announcementForm, {
    announcementId: '',
    title: '',
    content: '',
    type: '',
    status: '',
    imageUrl: '',
    createdAt: '',
    updatedAt: ''
  })
  if (announcementFormRef.value) {
    announcementFormRef.value.resetFields()
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 预览公告
const previewAnnouncement = () => {
  // 验证表单
  if (!announcementForm.title) {
    ElMessage.warning('请输入公告标题')
    return
  }

  if (!announcementForm.content) {
    ElMessage.warning('请输入公告内容')
    return
  }

  if (!announcementForm.type) {
    ElMessage.warning('请选择公告类型')
    return
  }

  previewVisible.value = true
}

// 关闭预览
const handlePreviewClose = () => {
  previewVisible.value = false
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.announcement-add-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 添加面包屑导航样式 */
.el-breadcrumb {
  margin-bottom: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.announcement-form {
  padding: 20px;
}

.announcement-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.announcement-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.announcement-uploader {
  width: 100%;
  display: block;
}

.announcement-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 178px;
}

.announcement-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.announcement-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.announcement-image-preview {
  width: 100%;
  height: 178px;
  object-fit: cover;
  display: block;
}

.upload-text {
  position: absolute;
  bottom: 10px;
  width: 100%;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.image-url-display {
  margin-top: 10px;
}

.image-url-input {
  width: 100%;
}

.form-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.editor-wrapper {
  border: 1px solid #ccc;
  border-radius: 6px;
  z-index: 100;
  width: 100%;
}

.editor-content {
  padding: 0 10px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

/* 让表单元素占满容器宽度 */
:deep(.el-form-item__content) {
  width: 100%;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

/* 预览样式 */
.preview-dialog {
  border-radius: 12px;
}

.preview-content {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.preview-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.preview-title {
  margin: 0 0 15px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  text-align: center;
}

.preview-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.preview-tag {
  margin: 0;
}

.preview-date {
  color: #909399;
  font-size: 14px;
}

.preview-image {
  text-align: center;
  margin: 20px 0;
}

.preview-image-content {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-body {
  margin-top: 20px;
  line-height: 1.8;
  color: #303133;
}

.preview-body :deep(p) {
  margin: 10px 0;
}

.preview-body :deep(h1) {
  font-size: 24px;
  margin: 20px 0 15px 0;
  font-weight: 600;
}

.preview-body :deep(h2) {
  font-size: 22px;
  margin: 18px 0 13px 0;
  font-weight: 600;
}

.preview-body :deep(h3) {
  font-size: 20px;
  margin: 16px 0 11px 0;
  font-weight: 600;
}

.preview-body :deep(h4) {
  font-size: 18px;
  margin: 14px 0 9px 0;
  font-weight: 600;
}

.preview-body :deep(h5) {
  font-size: 16px;
  margin: 12px 0 7px 0;
  font-weight: 600;
}

.preview-body :deep(strong) {
  font-weight: 600;
}

.preview-body :deep(em) {
  font-style: italic;
}

.preview-body :deep(u) {
  text-decoration: underline;
}

.preview-body :deep(ul) {
  padding-left: 20px;
  margin: 10px 0;
}

.preview-body :deep(ol) {
  padding-left: 20px;
  margin: 10px 0;
}

.preview-body :deep(li) {
  margin: 5px 0;
}

.preview-body :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

:deep(.el-dialog__body) {
  padding: 10px 20px 20px 20px;
}
</style>
